import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

//常用的路由直接引入
import Home from '../views/Home.vue';

// 用法如下
// import { useRouter } from 'vue-router';
// router.push('/home');

const routes: Array<RouteRecordRaw> = [
  { path: '/', redirect: '/home/analysis' },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'analysis',
        name: 'HomeAnalysis',
        component: () => import(/* webpackChunkName: "login" */ '@/views/home/Analysis.vue'),
      },
      {
        path: 'ltv',
        name: 'HomeLtv',
        component: () => import(/* webpackChunkName: "login" */ '@/views/home/Ltv.vue'),
      },
      {
        path: 'retained',
        name: 'HomeRetained',
        component: () => import(/* webpackChunkName: "login" */ '@/views/home/Retained.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/Login.vue'),
  },
  {
    path: '/404',
    name: 'Page404',
    component: () => import(/* webpackChunkName: "login" */ '@/views/404.vue'),
  },
  {
    path: '/:catchAll(.*)*',
    redirect: { name: 'Page404' },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  let tokenValue = window.localStorage.getItem('TOKEN');
  if (to.name !== 'Login' && !tokenValue) {
    next({ name: 'Login' });
  } else {
    next();
  }
});

export default router;
